package org.litu.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.litu.app.dao.SysUserRoleMapper;
import org.litu.app.entity.system.SysUserRole;
import org.litu.app.service.ISysUserRoleService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户角色服务实现类
 * </p>
 *
 * @author ltgk
 * @since 2018-10-23
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    /**
     * 根据userId查找，所有的角色ID
     *
     * @return
     */
    @Override
    public List<String> getByUserId(String userId) {
        List<String> result = new ArrayList<>();
        if (StringUtils.isBlank(userId)) {
            return result;
        }
        LambdaQueryWrapper<SysUserRole> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysUserRole::getUserId, userId);
        List<SysUserRole> roles = list(queryWrapper);
        for (SysUserRole role : roles) {
            result.add(role.getRoleId());
        }

        return result;
    }

    /**
     * 更新角色权限
     *
     * @param userId
     * @param roleIds
     * @return
     */
    @Override
    public boolean save(String userId, String roleIds) {
        if (StringUtils.isBlank(userId)) {
            return false;
        }
        // 整合处用户角色列表信息
        List<SysUserRole> entityList = new ArrayList<SysUserRole>();
        if (StringUtils.isNotBlank(roleIds)) {
            String[] roleIdsArr = roleIds.split(",");
            for (String roleId : roleIdsArr) {
                SysUserRole userRole = new SysUserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(userId);
                entityList.add(userRole);
            }
        }

        removeByUserId(userId);
        return super.saveBatch(entityList);
    }

    /**
     * 删除角色 的权限
     *
     * @param userId
     * @return
     */
    @Override
    public boolean removeByUserId(String userId) {
        if (StringUtils.isBlank(userId)) {
            return false;
        }
        LambdaQueryWrapper<SysUserRole> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysUserRole::getUserId, userId);
        return remove(queryWrapper);
    }

    /**
     * 根据权限id删除
     *
     * @param roleId
     * @return
     */
    @Override
    public boolean removeByRole(String roleId) {
        if (StringUtils.isBlank(roleId)) {
            return false;
        }
        LambdaQueryWrapper<SysUserRole> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysUserRole::getRoleId, roleId);
        return remove(queryWrapper);
    }
}
